<?php

class MY_Model extends CI_Model
{
	function __construct(){
		parent::__construct();
		// Load the Database Module REQUIRED for this to work.
		$this->load->database();//Without it -> Message: Undefined property: XXXController::$db
	}

	function get($select = "*", $table = "", $where = "", $order = "", $by = "DESC", $return_array = false)
	{
		$this->db->select($select);
		if($where != "")
		{
			$this->db->where($where);
		}
		#Query
		if($order != "" && (strtolower($by) == "desc" || strtolower($by) == "asc"))
		{
			if($order == 'rand'){
				$this->db->order_by('rand()');
			}else{
				$this->db->order_by($order, $by);
			}
		}		
		
		$query = $this->db->get($table);
		if($return_array){
			$result = $query->row_array();
		} else {
			$result = $query->row();
		}
		$query->free_result();
		return $result;
	}
    
	function fetch($select = "*", $table = "", $where = "", $order = "", $by = "DESC", $start = -1, $limit = 0, $return_array = false)
	{
		
		$this->db->select($select);
		if($where != "")
		{
			$this->db->where($where);
		}
		if($order != "" && (strtolower($by) == "desc" || strtolower($by) == "asc"))
		{
			if($order == 'rand'){
				$this->db->order_by('rand()');
			}else{
				$this->db->order_by($order, $by);
			}
		}
		
		if((int)$start >= 0 && (int)$limit > 0)
		{
			$this->db->limit($limit, $start);
		}
		#Query
		$query = $this->db->get($table);
		if($return_array){
			$result = $query->result_array();
		} else {
			$result = $query->result();
		}
		$query->free_result();
		return $result;
	}

	function fetch_join($select = "*", $table = "", $where = "", $join_1 = "", $table_1 = "", $on_1 = "", $join_2 = "", $table_2 = "", $on_2 = "", $order = "", $by = "DESC", $start = -1, $limit = 0, $distinct = false,$return_array = false)
	{
        $this->db->select($select);
		if(($join_1 == "INNER" || $join_1 == "LEFT" || $join_1 == "RIGHT") && $table_1 != "" && $on_1 != "")
		{
			$this->db->join($table_1, $on_1, $join_1);
		}
		if(($join_2 == "INNER" || $join_2 == "LEFT" || $join_2 == "RIGHT") && $table_2 != "" && $on_2 != "")
		{
			$this->db->join($table_2, $on_2, $join_2);
		}
		if($where != "")
		{
			$this->db->where($where);
		}
		if($order != "" && (strtolower($by) == "desc" || strtolower($by) == "asc"))
		{
            $this->db->order_by($order, $by);
		}
		if((int)$start >= 0 && (int)$limit > 0)
		{
			$this->db->limit($limit, $start);
		}
		if($distinct == true)
		{
			$this->db->distinct();
		}
		#Query
		$query = $this->db->get($table);
		if($return_array){
			$result = $query->result_array();
		} else {
            $result = $query->result();
		}
		$query->free_result();
		return $result;
	}

	function insert($table = "", $data)
	{
		return $this->db->insert($table, $data);
	}

	function update($table = "", $data, $where = "")
	{
    	if($where != "")
    	{
            $this->db->where($where);
    	}
		return $this->db->update($table, $data);
	}

	function delete($table = "", $where = "")
    {
		if($where != "")
    	{
            $this->db->where($where);
    	}
		return $this->db->delete($table);
    }
    
	function Upload($file='', $uploadDir='') {
		if($file['error']!=0 || empty($uploadDir)) return false;

		Newfolder($uploadDir);
		$tmp_name= $file['tmp_name'];
		$path_parts = pathinfo($file['name']);
		$path_parts['dirname'];
		$path_parts['basename'];
		$path_parts['extension'];
		$path_parts['filename'];
		
		//TODO: Lay extesion
		$ext = ".".strtolower($path_parts['extension']);
		$name = md5(uniqid(mt_rand())).'_'.time().$ext;

		if(move_uploaded_file($tmp_name, $uploadDir.$name)) {
			//Upload  thanh cong
			return $name;
		}else {
			return false;
		}//else
	}//Upload     

	function send_email($data= '') {
		$this->load->library('email');
		$config['useragent'] = USERAGENT;		

		$config['mailtype'] = 'html';
	

		$this->email->initialize($config);
			
		$this->email->from('no-reply'.rand(1,9999).'@c2life.com.vn', EMAIL_NAME);
		$this->email->to($data['email']);
		$this->email->subject($data['subject']);
		$this->email->message($data['html']);
		if($this->email->send()) {
			return true;
		}else{
			return $this->email->print_debugger();
		}
	}
	function getSetting($slug=''){
		$this->db->select('*');
		if($slug!=''){
			$this->db->where('slug', $slug);
			$this->db->limit(1);
		}
		$query = $this->db->get('admin_nqt_settings');

		if($query->result()){
			return $query->row();
		}else{
			return false;
		}
	}
	
	// function chí
    public function get_data($params, $type = "object") {
        if (isset($params["select"])) {
            $this->db->select($params["select"]);
        }

        if (isset($params["where"])) {
            $this->db->where($params["where"]);
        }

        if (isset($params["join"])) {
            $i = 0;
            foreach ($params["join"]['table'] as $k => $v) {
                if (isset($params["join"]['type'])) {
                    if (is_array($params["join"]['type'])) {
                        $this->db->join(PREFIX . $k, $v, $params["join"]['type'][$i]);
                    } else {
                        $this->db->join(PREFIX . $k, $v, $params["join"]['type']);
                    }
                } else {
                    $this->db->join(PREFIX . $k, $v);
                }
                $i++;
            }
        }

        if (isset($params["or_where"])) {
            foreach ($params["or_where"] as $k => $v) {
                $this->db->or_where($k, $v);
            }
        }

        if (isset($params["where_in"])) {
            foreach ($params["where_in"] as $k => $v) {
                $this->db->where_in($k, $v);
            }
        }

        if (isset($params["or_where_in"])) {
            foreach ($params["or_where_in"] as $k => $v) {
                $this->db->or_where_in($k, $v);
            }
        }

        if (isset($params["where_not_in"])) {
            foreach ($params["where_not_in"] as $k => $v) {
                $this->db->where_not_in($k, $v);
            }
        }

        if (isset($params["or_where_not_in"])) {
            foreach ($params["or_where_not_in"] as $k => $v) {
                $this->db->or_where_not_in($k, $v);
            }
        }
        if (isset($params["group_by"])) {
            $this->db->group_by($params["group_by"]);
        }

        if (isset($params["having"])) {
            $this->db->having($params["having"]);
        }

        if (isset($params["or_having"])) {
            $this->db->or_having($params["having"]);
        }

        if (isset($params["like"])) {
            foreach ($params["like"] as $k => $v) {
                $this->db->like($k, $v);
            }
        }

        if (isset($params["or_like"])) {
            foreach ($params["or_like"] as $k => $v) {
                $this->db->or_like($k, $v);
            }
        }

        if (isset($params["not_like"])) {
            foreach ($params["not_like"] as $k => $v) {
                $this->db->not_like($k, $v);
            }
        }

        if (isset($params["or_not_like"])) {
            foreach ($params["or_not_like"] as $k => $v) {
                $this->db->not_like($k, $v);
            }
        }

        if (isset($params["order_by"])) {
            if(is_array($params["order_by"])){
                foreach ($params["order_by"] as $k => $v) {
                    $this->db->order_by($k, $v);
                }
            }  else {
                $this->db->order_by($params["order_by"]);
            }
        }
        if (isset($params["distinct"])) {
            $this->db->distinct();
        }

        if (isset($params["limit"])) {
            $limit = explode(',', $params["limit"]);
            if (count($limit) > 1) {
                $this->db->limit($limit[0], $limit[1]);
            } else {
                $this->db->limit($params["limit"]);
            }
        }

        $query = $this->db->get(PREFIX . $params["table"]);
        if ($type == "object")
            $data= $query->result();
        else if ($type == "array")
            $data= $query->result_array();
        else if ($type == "row")
            $data= $query->first_row();
        if($data){
            return $data;
        }
    }
    function get_all($table, $where = array()) {
        if (count($where) > 0)
            $this->db->where($where);
        
        $query = $this->db->get(PREFIX . $table);
        if ($query->result())
            return $query->result();
        else
            return false;
    }
    function row_data($table, $where = array()) {
        if (count($where) > 0)
            $this->db->where($where);
        $this->db->order_by('id', 'DESC');
        $query = $this->db->get(PREFIX . $table);
        if ($query->result())
            return $query->first_row();
        else
            return false;
    }
    
    function count_data($table, $where = array()) {
        if (count($where) > 0)
            $this->db->where($where);
        $query = $this->db->get(PREFIX . $table);
        return $query->num_rows();
    }

    function insert_data($table, $array = array()) {
        $this->db->set($array);
        $this->db->insert(PREFIX . $table);
        return $this->db->affected_rows();
    }

    function insert_id($table, $array = array()) {
        $this->db->set($array);
        $this->db->insert(PREFIX . $table);
        return $this->db->insert_id();
    }

    function update_cong($table, $f, $id = '') {
        $this->db->set("$f", "$f + 1", FALSE);
        $this->db->where('id', $id);
        $this->db->update(PREFIX . $table);
    }
	function update_tru($table, $f, $id = '') {
        $this->db->set("$f", "$f - 1", FALSE);
        $this->db->where('id', $id);
        $this->db->update(PREFIX . $table);
    }
	function update_value($table, $f,$v, $where = array()) {
        $this->db->set("$f", "$f - $v", FALSE);
        $this->db->where($where);
        $this->db->update(PREFIX . $table);
    }

    function update_data($table, $data = array(), $where = array()) {
        $this->db->set($data);
        $this->db->update(PREFIX . $table, $data, $where);
        return $this->db->affected_rows();
    }

    function delete_data($table, $where = array())
    {
        $this->db->where($where);
        $this->db->delete(PREFIX . $table);
        return $this->db->affected_rows();
    }
}